<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form" v-if="headerShow">
                <a-form size="small" :model="pageData" layout="inline">
                    <a-form-item label="设备管理">
                        <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                            v-model="pageData.dropDownData" @press-enter="huiche" />
                    </a-form-item>
                </a-form>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
            <div class="my-tool-bar">
                <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler">
                </Toolbar>
            </div>
        </template>
        <template #pageTabel>
            <a-tabs   :lazy-load="true" :justify="true">
                <a-tab-pane>
                      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                        :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc">
                    </AgGridVuesCopys>
                </a-tab-pane>
            </a-tabs>
        </template>
        <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
            style="justify-content: center" />

        <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 999 }" :mask-closable="false"
            unmount-on-close popup-container=".arco-tabs-content" height="100%" :visible="pageData.showAdd"
            :ok-loading="pageData.pageLoading" placement="bottom" @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label="设备编号" field="sectionName">
                        <a-input placeholder=" " v-model="dataForm.equipmenCode" />
                    </a-form-item>
                    <a-form-item label-col-flex="80px" label="工序名称" field="processName"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '工序名称必填' }]">
                        <a-input placeholder=" " v-model="dataForm.equipmenCode" />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import { AnyARecord } from 'dns';

import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'

interface BrandInfo {
    "id": any,
    "equipmenCode": any,
    "equipmenName": any,
    "equipmenModel": any,
    "equipmenSpecs": any,
    "tube": any,
    "department": any,
    "lowest": any,
    "highest": any,
    "auxiliaryWater": any,
    "auxiliaryCoefficient": any,
    "auxiliaryHighestWater": any,
    "deviceCapacity": any,
    "capacityUnit": any,
    "process": any,
    "section": any,
    "lowestBath": any,
    "controlMark": any,
    "controlCode": any,
    "power": any,
    "equipmenStatus": any,
    "propertyCode": any,
    "remarks": any,
}

export default {
    name: "DeviceList",
    setup() {
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            pagination.page = val
            doRefresh();
        }

        function change1(val: any) {
            pagination.pageSize = val
            doRefresh();
        }
        const headerShow = ref<boolean>(true)
        //查询方法
        function doRefresh() {

            pageData.pageLoading = true
            post({
                url: "/pdm/worksectionWorkprocedure/selectPage",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: "0",
                    processName: pageData.dropDownData
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        gridOption.value.setRowData(data.list);
                        total.value = data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "设备编号",
                key: "id",
                dataIndex: "id",
                width: 150,
            },
            {
                title: "设备名称",
                key: "sectionName",
                dataIndex: "sectionName",
                width: 150
            },
            {
                title: "设备型号/容量",
                key: "processName",
                dataIndex: "processName",
                width: 150
            },
            {
                title: "设备规格",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "管型",
                key: "id",
                dataIndex: "id",
                width: 150,
            },
            {
                title: "采购部门",
                key: "sectionName",
                dataIndex: "sectionName",
                width: 150
            },
            {
                title: "最低水位",
                key: "processName",
                dataIndex: "processName",
                width: 150
            },
            {
                title: "最高水位",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "副缸系数",
                key: "id",
                dataIndex: "id",
                width: 150,
            },
            {
                title: "副缸最高水位",
                key: "sectionName",
                dataIndex: "sectionName",
                width: 150
            },
            {
                title: "设备产能",
                key: "processName",
                dataIndex: "processName",
                width: 150
            },
            {
                title: "产能单位",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "工序",
                key: "id",
                dataIndex: "id",
                width: 150,
            },
            {
                title: "工段",
                key: "sectionName",
                dataIndex: "sectionName",
                width: 150
            },
            {
                title: "最低浴比",
                key: "processName",
                dataIndex: "processName",
                width: 150
            },
            {
                title: "对应中控代号",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "对应中控编号",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "装机功率",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "设备状态",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "固定资产编号",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "登记日期",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 200
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 200
            },
            {
                title: '操作',
                key: "id",
                slotName: 'act',
                width: 150, fixed: 'right'
            }
        ]);
        let tc: any[] = tableColumns.map((o) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            if (o.slotName === 'act') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"

                obj['cellRenderer'] = {
                    template: `<a-space>
                                   <a-tag color="#ff7d00" @click="a1">修改</a-tag>
                                   
                               </a-space>`,
                    setup(props: any) {
                        const a1 = () => {
                            editHandler(props.params.data)
                        }

                        return {
                            a1,

                        }
                    }

                }
            }

            return obj
        })



        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)

        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            nameList: [],
            pageLoading: boolean,
            typeList: [],
            dropDownData1: any,
            rHeight: any,
            btnList: any[],
            isEdit: boolean,
            sectionNames: []
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增设备列表',
            dropDownData: "",
            pageLoading: false,
            typeList: [],
            dropDownData1: "",
            rHeight: 0,
            btnList: [],
            isEdit: false,
            sectionNames: []
        });

        interface gcType {
            id: any,
            company: any,
        }
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ "processName": "" });
        }

        //下拉数据
        const options = ref<any>(pageData.nameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { processName: value, deleteState: 0 }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "/pdm/worksectionWorkprocedure/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data);
                    let dataList: any = [];
                    data.forEach(function (o: any) {
                        dataList.push(o["processName"])
                    });
                    pageData.nameList = dataList;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        const focusSel2 = () => {
            selCxAll2({ "sectionName": "", deleteState: 0 });
        }
        const options2 = ref<any>(pageData.sectionNames);
        const loadings2 = ref(false);
        const handleSearch2 = (value: any) => {
            if (value) {
                const ob = { boxName: value, deleteState: 0 }
                loadings2.value = true;
                selCxAll2(ob);
                options2.value = pageData.sectionNames;
                loadings2.value = false;
            } else {
                options2.value = []
            }
        };
        function selCxAll2(val: any) {
            post({
                url: "/pdm/worksection/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.sectionNames = data;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        onMounted(() => {
            // 切换tap到本页面执行的方法
            emitter.on("OperationDefinition", () => {
                // selCxAll({});
                doRefresh();
            });
        });

        let cxbl = {}
        //查询
        const selectHandler = () => {
            pagination.page = 1
            cxbl = pageData.dropDownData
            doRefresh();
        }
        const queryData = reactive({
            processName: ""
        });
        const addHandler = () => {
            for (var key in dataForm) {
                dataForm[key] = null;

            }
            pageData.showAdd = true
            pageData.sideTitle = '新增设备列表'
        }
        const dataForm = reactive<BrandInfo>({
            "id": null,
            "equipmenCode": null,
            "equipmenName": null,
            "equipmenModel": null,
            "equipmenSpecs": null,
            "tube": null,
            "department": null,
            "lowest": null,
            "highest": null,
            "auxiliaryWater": null,
            "auxiliaryCoefficient": null,
            "auxiliaryHighestWater": null,
            "deviceCapacity": null,
            "capacityUnit": null,
            "process": null,
            "section": null,
            "lowestBath": null,
            "controlMark": null,
            "controlCode": null,
            "power": null,
            "equipmenStatus": null,
            "propertyCode": null,
            "remarks": null,
        })
        // 表格准备事件
        const gridOption = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
        }

        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {

                    pageData.pageLoading = true;

                    if (pageData.sideTitle === "新增设备列表") {
                        post({
                            url: "/pdm/worksectionWorkprocedure/insert",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                            doRefresh();
                        }).finally(() => {
                            doRefresh();
                            pageData.pageLoading = false
                        })
                    } else {
                        post({
                            url: "/pdm/worksectionWorkprocedure/update",
                            data: [dataForm],
                        }).then((res: any) => {
                            if (res.code === 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                            //doRefresh();
                        }).finally(() => {
                            doRefresh();
                            pageData.pageLoading = false
                        })
                    }
                }

            })
        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: '/pdm/worksectionWorkprocedure/delete',
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                            pagination.page = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: '修改失败',
                                duration: 5000
                            })
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                }
            })
        }
        const editHandler = (record: BrandInfo) => {
            selCxAll1({ key: "" })
            //循环对象 赋值
            for (let key in record) {
                dataForm[key] = record[key]
            }
            pageData.sideTitle = '修改'
            pageData.showAdd = true
        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })
        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {
            // dataForm.sectionCode = dataForm.sectionCode.toUpperCase();
        }

        //下拉数据
        const options1 = ref<any>(pageData.nameList);
        const loading1 = ref(false);
        const handleSearch1 = (value: any) => {
            if (value) {
                const ob = {
                    key: value,
                    deleteState: 0
                }
                loading.value = true;
                selCxAll1(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询 
        function selCxAll1(val: any) {
            post({
                url: "/pdm/workprocedure/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.nameList = data;
                } else {
                    // Message.error({
                    //     content: "查询失败！",
                    //     duration: 5000,
                    // });
                }
            });
        }

        //下拉框得到焦点
        const focusSel1 = () => {
            selCxAll1({ "key": "" });
        }

        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            // flex: 1
        }

        const huiche = () => {
            doRefresh()
        }
        return {
            huiche,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            isChiese,
            inputBlur,
            options,
            loading,
            handleSearch,
            focusSel,
            focusSel2,
            options1,
            loading1,
            options2,
            loadings2,
            handleSearch1,
            handleSearch2,
            focusSel1,
            headerShow,
            handleChange,
            PageSize,
            change1,
            defaultColDef,
            tc,
            gridOption,
            gridReady,
            total,
            page,
            size,
        };
    },
    components: { Toolbar, PageTabelLayout, QrcodeVue }
}
</script>
